package com.margo.project;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

/**           
 * https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D
 * 
 * https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E6%B5%81%E6%A1%86%E6%9E%B6%E7%9A%84%E9%80%82%E9%85%8D#dubbo
 * @author fangxingbang
 *
 */
@SpringBootApplication
public class SpringSentinelApplication {
	public static void main(String[] args) {
		initFlowRules();  //流控
		//initDegradeRule(); //熔断
		SpringApplication.run(SpringSentinelApplication.class, args);
	}
	
	private static void initFlowRules(){
	    List<FlowRule> rules = new ArrayList<>();
	    FlowRule rule = new FlowRule();
	    rule.setResource("getOrderInfo");
	    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
	    // Set limit QPS to 20.
	    rule.setCount(2);
	    rules.add(rule);
	    FlowRuleManager.loadRules(rules);
	}
	
	public static void initDegradeRule(){
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        //下面这个配置的意思是，当1s内持续进入5个请求，平均响应时间都超过count(10ms),
        // 那么在接下来的timewindow(10s)内，对
        //这个方法的调用都会自动熔断，抛出异常:degradeException.
        //指定被保护的资源
        rule.setResource("getOrderInfo");
        //降级模式, RT（平均响应时间）、异常比例(DEGRADE_GRADE_EXCEPTION_RATIO)/异常数量
        //5个异常降级
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        rule.setCount(5); //阈值  触发降级
        rule.setTimeWindow(60);//降级的时间单位, 单位为s
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
	}
}
